import sys
from PySide6.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QVBoxLayout, QWidget
from PySide6.QtGui import QPainterPath, QPen, QPainter
from PySide6.QtCore import Qt, QTimer

class RealTimePlot(QGraphicsView):
    def __init__(self, parent=None):
        super(RealTimePlot, self).__init__(parent)
        self.setScene(QGraphicsScene())
        self.setRenderHint(QPainter.Antialiasing)

        # 设置场景大小
        self.scene().setSceneRect(0, 0, 800, 400)
        self._data = [0] * 100  # 假设我们有100个点的数据
        self._paths = []  # 用于存储每个值对应的路径

        for _ in range(8):  # 创建8条曲线
            path = QPainterPath()
            pen = QPen(Qt.GlobalColor(_ % 7 + 1))  # 循环使用不同的颜色
            pen.setWidth(2)
            self._paths.append((path, pen))

        # 定时器，每500毫秒调用一次update_plot方法
        self._timer = QTimer(self)
        self._timer.timeout.connect(self.update_plot)
        self._timer.start(100)

    def update_plot(self):
        # 更新数据（在实际应用中应该从数据源获取）
        new_data = self.generate_new_data()

        # 移动所有路径以反映新的数据点
        for i, (path, _) in enumerate(self._paths):
            path.clear()  # 清除旧路径
            for j, value in enumerate(new_data):
                x = j * 8  # 每个点之间间隔8像素
                y = 400 - value * 10  # 将值转换为Y坐标
                if j == 0:
                    path.moveTo(x, y)
                else:
                    path.lineTo(x, y)

        # 更新场景
        self.scene().clear()
        for path, pen in self._paths:
            self.scene().addPath(path, pen)

    def generate_new_data(self):
        # 这里简单地生成一些随机数据作为示例
        import random
        return [random.randint(0, 40) for _ in range(100)]

# 主程序入口
if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = QWidget()
    layout = QVBoxLayout(main_window)
    plot = RealTimePlot()
    layout.addWidget(plot)
    main_window.show()
    sys.exit(app.exec())